package com.ruben.validator;

import com.ruben.enumeration.GenderEnum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName: GenderValidator
 * @Description:
 * @Date: 2020/8/18 19:25
 * *
 * @author: achao<achao1441470436 @ gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
public class GenderValidator implements ConstraintValidator<Gender, Integer> {

    private static final Set<Integer> GENDER_CONSTRAINTS = new HashSet<>();

    /**
     * Initializes the validator in preparation for
     * calls.
     * The constraint annotation for a given constraint declaration
     * is passed.
     * <p>
     * This method is guaranteed to be called before any use of this instance for
     * validation.
     * <p>
     * The default implementation is a no-op.
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(Gender constraintAnnotation) {
        GENDER_CONSTRAINTS.addAll(Arrays
                .stream(constraintAnnotation.value())
                .map(GenderEnum::getCode)
                .collect(Collectors.toSet()));
    }

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return GENDER_CONSTRAINTS.contains(value);
    }
}
